<template>
    <div class="medical-container">
      <!-- 查询功能区 -->
      <div class="query-section">
        <el-input 
          v-model="queryUserId" 
          placeholder="输入用户ID" 
          style="width: 200px; margin-right: 15px"
          type="number"
        />
        <el-button type="primary" @click="handleUserQuery">查询用户记录</el-button>
        <el-button @click="showAllRecords">显示全部记录</el-button>
        <el-button type="success" @click="showAddDialog" style="margin-left: auto">新增记录</el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table
        :data="medicalData"
        v-loading="loading"
        border
        highlight-current-row
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="medicalId" label="记录ID" width="100" align="center" />
        <el-table-column prop="userId" label="用户ID" width="100" align="center" />
        <el-table-column prop="medicalHistory" label="病史" min-width="150" show-overflow-tooltip />
        <el-table-column prop="treatmentPlan" label="治疗方案" min-width="200" show-overflow-tooltip />
        <el-table-column prop="medications" label="用药" width="120" />
        <el-table-column prop="treatmentStart" label="治疗开始" width="120" align="center" />
        <el-table-column prop="treatmentEnd" label="治疗结束" width="120" align="center" />
        <el-table-column prop="createdAt" label="创建时间" width="180" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button link type="danger" @click="deleteRecord(row.medicalId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 新增记录弹窗 -->
      <el-dialog v-model="addDialogVisible" title="新增医疗记录" width="600px">
        <el-form ref="addForm" :model="newRecord" :rules="formRules" label-width="100px">
          <el-form-item label="用户ID" prop="userId">
            <el-input-number v-model="newRecord.userId" :min="1" controls-position="right" />
          </el-form-item>
          <el-form-item label="病史" prop="medicalHistory">
            <el-input v-model="newRecord.medicalHistory" type="textarea" :rows="2" />
          </el-form-item>
          <el-form-item label="治疗方案" prop="treatmentPlan">
            <el-input v-model="newRecord.treatmentPlan" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="用药" prop="medications">
            <el-input v-model="newRecord.medications" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始日期" prop="treatmentStart">
                <el-date-picker
                  v-model="newRecord.treatmentStart"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="treatmentEnd">
                <el-date-picker
                  v-model="newRecord.treatmentEnd"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确认提交</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { 
    getMedicalRecordInfo,
    getMedicalRecordListByUserId,
    addMedicalRecord,
    deleteMedicalRecord
  } from '@/api/medicalRecord'
  
  // 响应式数据
  const medicalData = ref([])
  const loading = ref(false)
  const queryUserId = ref('')
  const addDialogVisible = ref(false)
  
  // 新增记录表单
  const addForm = ref(null)
  const newRecord = ref({
    userId: '',
    medicalHistory: '',
    treatmentPlan: '',
    medications: '',
    treatmentStart: '',
    treatmentEnd: ''
  })
  
  // 表单验证规则
  const formRules = {
    userId: [
      { required: true, message: '请输入用户ID', trigger: 'blur' },
      { type: 'number', message: '必须为数字值' }
    ],
    medicalHistory: [
      { required: true, message: '请输入病史信息', trigger: 'blur' }
    ],
    treatmentStart: [
      { required: true, message: '请选择开始日期', trigger: 'change' }
    ]
  }
  
  // 生命周期钩子
  onMounted(async () => {
    await loadAllRecords()
  })
  
  // 加载全部记录
  const loadAllRecords = async () => {
    try {
      loading.value = true
      const response = await getMedicalRecordInfo({})
      medicalData.value = response.data || []
    } catch (error) {
      ElMessage.error('数据加载失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 显示全部记录
  const showAllRecords = async () => {
    await loadAllRecords()
    ElMessage.success('已显示全部记录')
  }
  
  // 用户ID查询处理
  const handleUserQuery = async () => {
    if (!queryUserId.value) {
      ElMessage.warning('请输入用户ID')
      return
    }
    
    try {
      loading.value = true
      const response = await getMedicalRecordListByUserId(Number(queryUserId.value))
      medicalData.value = response.data || []
      ElMessage.success(`找到${response.data.length}条记录`)
    } catch (error) {
      ElMessage.error('查询失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 删除记录
  const deleteRecord = (medicalId) => {
    ElMessageBox.confirm('确认删除该记录？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await deleteMedicalRecord({ medicalId })
        medicalData.value = medicalData.value.filter(
          item => item.medicalId !== medicalId
        )
        ElMessage.success('删除成功')
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    }).catch(() => {})
  }
  
  // 新增记录处理
  const submitAddForm = async () => {
    await addForm.value.validate()
    try {
      const response = await addMedicalRecord({
        ...newRecord.value,
        userId: Number(newRecord.value.userId)
      })
      
      if (response.code === '000') {
        medicalData.value = [response.data, ...medicalData.value]
        addDialogVisible.value = false
        addForm.value.resetFields()
        ElMessage.success('记录添加成功')
      }
    } catch (error) {
      ElMessage.error('添加失败: ' + error.message)
    }
  }
  
  // 显示新增弹窗
  const showAddDialog = () => {
    addDialogVisible.value = true
  }
  </script>
  
  <style scoped>
  .medical-container {
    padding: 20px;
    background-color: #f5f7fa;
  }
  
  .query-section {
    display: flex;
    gap: 15px;
    padding: 15px;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
  
  .el-table {
    margin-top: 20px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
  
  .el-form-item {
    margin-bottom: 22px;
  }
  </style>